package com.zhhtech.zhh.ui.helper

import android.content.Intent
import androidx.fragment.app.FragmentActivity
import androidx.lifecycle.LifecycleOwner
import com.zhhtech.zhh.BuildConfig
import com.zhhtech.zhh.R
import com.zhhtech.zhh.api.api
import com.zhhtech.zhh.api.core.launchUI
import com.zhhtech.zhh.ui.api.ApiObserver
import com.zhhtech.zhh.ui.ext.DefaultLifecycleObserver
import com.zhhtech.zhh.ui.ext.toColor
import com.zhhtech.zhh.ui.ext.toastMessageLong
import com.xuexiang.xupdate.XUpdate
import com.xuexiang.xupdate.entity.DownloadEntity
import com.xuexiang.xupdate.entity.UpdateEntity
import com.xuexiang.xupdate.utils.UpdateUtils

const val ACTION_REQUEST = "ACTION_REQUEST"

object AppUpdateHelper : DefaultLifecycleObserver, Receiver {

    private const val CHECK_UPDATE_INTERVAL = 60 * 60 * 1000
    private var activity: FragmentActivity? = null
    private var lastCheckUpdateTime: Long = System.currentTimeMillis()
    private var isCheckUpdate = false

    fun FragmentActivity.initUpdate() {
        if (activity != null) {
            return
        }
        activity = this
        lifecycle.addObserver(AppUpdateHelper)
        localRegisterReceiver(ACTION_REQUEST, AppUpdateHelper)
        checkUpdate(activity)
    }

    fun manualCheckUpdate(activity: FragmentActivity) {
        isCheckUpdate = false
        checkUpdate(activity, true)
    }

    private fun checkUpdate(activity: FragmentActivity? = null, showNoUpdateTips: Boolean = false) {
        // 超过一个小时从新检查一次
        if (isCheckUpdate && System.currentTimeMillis() - lastCheckUpdateTime > CHECK_UPDATE_INTERVAL) {
            isCheckUpdate = false
        }
        if (!isCheckUpdate) {
            isCheckUpdate = true
            activity?.launchUI({
                val appConfig = api.version(BuildConfig.VERSION_NAME)
                if (appConfig.isOk && appConfig.data != null && appConfig.data!!.updateStatus > 0
                    && appConfig.data?.downloadUrl?.isNotEmpty() == true
                ) {
                    val url = appConfig.data?.downloadUrl
                    val updateEntity = UpdateEntity().apply {
                        isHasUpdate = true
                        isForce = appConfig.data!!.updateStatus == 2
                        setIsIgnorable(false)
                        versionCode = BuildConfig.VERSION_CODE
                        versionName = BuildConfig.VERSION_NAME
                        updateContent = appConfig.data?.remark?.ifEmpty { "有新版本" }
                        downLoadEntity = DownloadEntity()
                            .setCacheDir(UpdateUtils.getDefaultDiskCacheDirPath())
                            .setDownloadUrl(url)
                        setIsSilent(false)
                        setIsAutoInstall(true)
                    }
                    XUpdate.newBuild(activity)
                        .promptThemeColor(R.color.main_color.toColor())
//                        .promptTopResId(R.mipmap.bg_update_top)
//                        .promptButtonTextColor(Color.WHITE)
                        .build()
                        .update(updateEntity)
                } else if (showNoUpdateTips) {
                    "当前已是最新版本！".toastMessageLong()
                }
                lastCheckUpdateTime = System.currentTimeMillis()
            }, ApiObserver(activity, showLoadingDialog = false), error = {
                isCheckUpdate = false
            })
        }
    }

    override fun onDestroy(owner: LifecycleOwner) {
        owner.lifecycle.removeObserver(AppUpdateHelper)
        activity = null
    }

    override fun invoke(intent: Intent) {
        checkUpdate()
    }
}

